<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\exception\ValidateException;
use think\facade\Queue;
use EasyWeChat\Factory;


// 轻学堂书籍
class Book extends BaseController
{


    public function index()
    {
        $cate = Db::name('qxt_courses')
            ->distinct(true)
            ->where('type', '=', 2)
            ->field('category')
            ->select();
        View::assign('category', $cate);
        return View::fetch();
    }


    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];


        if (isset($get['courseTitle'])) {
            if (!empty($get['courseTitle'])) {
                $where[] = ['courseTitle', 'like', '%'.$get['courseTitle'].'%'];
            }
        }


        if (isset($get['category'])) {
            if (!empty($get['category'])) {
                $where[] = ['category', 'like', '%'.$get['category'].'%'];
            }
        }

        if (isset($get['lecturer'])) {
            if (!empty($get['lecturer'])) {
                $where[] = ['lecturerName', 'like', '%'.$get['lecturer'].'%'];
            }
        }

        if (isset($get['mediaType'])) {
            if(!empty($get['mediaType'])){
                $where[] = ['mediaType', '=', $get['mediaType']];
            }
        }

        if (isset($get['using'])) {
            if(!empty($get['using'])) {
                $where[] = ['using', '=', $get['using']];
            }
        }

        $where[] = ['status', '=', 1];
        $where[] = ['type', '=', 2];

        $total = Db::name('qxt_courses')
            ->where($where)
            ->count();

        $rows = Db::name('qxt_courses')
            ->where($where)
            ->order('id', 'asc')
            ->page($get['page'], $get['limit'])
            ->select()->toArray();
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }



    //+课程同步
    public function synchronization()
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $old_num = 0;
        $new_num = 0;
        for ($i = 0; $i <= 5000; $i+=100) {
            $count = 100;
            $string = "appId=".config('app.school.appid')."&count=".$count."&offset=".$i."&appSecret=".config('app.school.secret');
            $sign = strtoupper(md5($string));
            $url = "https://www.qingxuetang.com/open/api/content/getBooks?appId=".config('app.school.appid')."&offset=".$i."&count=".$count."&sign=".$sign;

            $res = json_decode(http_get($url),true);
            if (empty($res['data']['dataList'])) {
                break;
            } else {
                foreach ($res['data']['dataList'] as &$v) {
                    $inf = Db::name('qxt_courses')->where('courseCode', '=', $v['bookCode'])->find();

                    if ($inf) {
                        $update = array(
                            'id'                => $inf['id'],
                            'courseCode'        => $v['bookCode'],
                            'mediaType'         => $v['bookType'],
                            'courseTitle'       => $v['bookTitle'],
                            'courseSubTitle'    => $v['bookSubTitle'],
                            'courseCover'       => $v['bookCover'],
                            'category'          => isset($v['category']) == false ? '' : $v['category'],
                            'author'            => isset($v['bookAuthor']) ? $v['bookAuthor']:'',
                            'lecturerName'      => $v['lecturerName'],
                            'lecturerAvatar'    => $v['lecturerAvatar'],
                            'lecturerIntro'     => $v['lecturerIntro'],
                            'linkUrl'           => $v['linkUrl'],
                            'updateCount'       => isset($v['updateCount']) ? $v['updateCount']:0,
                            'totalCount'        => isset($v['totalCount']) ? $v['totalCount']:0,
                            'latestUpdateTime'  => substr($v['latestUpdateTime'],0,10),
                            'duration'          => $v['duration'],
                            'update_time'       => time(),
                            'using'             => $inf['using']
                        );
                        if (isset($v['duration'])) {
                            $update['duration'] = $v['duration'];
                        } else {
                            $update['duration'] = 0;
                        }
                        Db::name('qxt_courses')->update($update);
                        $old_num++;
                    } else {
                        $insert = array(
                            'courseCode'        => $v['bookCode'],
                            'mediaType'         => $v['bookType'],
                            'courseTitle'       => $v['bookTitle'],
                            'courseSubTitle'    => $v['bookSubTitle'],
                            'courseCover'       => $v['bookCover'],
                            'category'          => $v['category'],
                            'author'            => isset($v['bookAuthor']) ? $v['bookAuthor']:'',
                            'lecturerName'      => $v['lecturerName'],
                            'lecturerAvatar'    => $v['lecturerAvatar'],
                            'lecturerIntro'     => $v['lecturerIntro'],
                            'totalCount'        => isset($v['totalCount']) ? $v['totalCount']:0,
                            'linkUrl'           => $v['linkUrl'],
                            'latestUpdateTime'  => substr($v['latestUpdateTime'],0,10),
                            'updateCount'       => isset($v['updateCount']) ? $v['updateCount']:0,
                            'hasFinished'       => 1,
                            'duration'          => $v['duration'],
                            'add_time'          => time(),
                            'update_time'       => time(),
                            'using'             => 1,
                            'type'              => 2,
                        );
                        if (isset($v['duration'])) {
                            $insert['duration'] = $v['duration'];
                        } else {
                            $insert['duration'] = 0;
                        }
                        Db::name('qxt_courses')->insertGetId($insert);
                        $new_num++;
                    }
                }
            }
        }

        return $this->outputAjax('同步成功！',0, ['new' => $new_num, 'old' => $old_num]);
    }

    // 分享二维码
    public function getQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/flex/pages/XiMaLaYa/index';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 280,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);
            return $this->outputAjax('获取成功', 0, ['url' => $qr]);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function downloadQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');
        $title = $request->param('title');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/flex/pages/XiMaLaYa/index';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 1280,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);

            $fileTmp = pathinfo($qr);
            $fileExt = $fileTmp['extension'];    //图片后缀名
            $filename = str_replace('.', '', $title);   //图片名称，可以任务设置图片名称
            $saveFileName = ($filename.'.'.$fileExt);
            $fp = fopen($qr,"r");
            //下载文件需要用到的头
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Content-Disposition: attachment; filename=".$saveFileName);
            $buffer = 1024;
            $file_count = 0;
            //向浏览器返回数据
            while (!feof($fp)) {
                $file_con = fread($fp,$buffer);
                $file_count += $buffer;
                echo $file_con;
            }
            fclose($fp);
            exit;
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    /**
     * 详情
     * @date: 2019年9月29日
     * @author: Administrator
     * @return:
     */
    public function view(Request $request)
    {
        $id = $request->get('id');
        $inf = Db::name('qxt_courses')->where('id', $id)->find();
        View::assign('inf', $inf);
        return View::fetch();
    }



    //+课程隐藏or显示
    public function toggle(Request $request)
    {
        if (!$id = $request->param('id')) {
            return $this->outputAjax();
        }
        try {
            $inf = Db::name('qxt_courses')->field('using')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['using'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $using = $inf['using'] == 1 ? 2 : 1;

            $update = array(
                'id'=> $id,
                'using'=> $using,
            );
            if(Db::name('qxt_courses')->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    // 课程学员
    public function members(Request $request)
    {
        $school_id = $request->get('id');
        View::assign('school_id',$school_id);
        return View::fetch();
    }


    public function getMembersList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $school_id = $request->get('school_id');
        $get = $request->get();

        $where = [];

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['b.userid', 'like', '%'.$get['keys'].'%'];
            }
        }

        if (isset($get['sign_out'])) {
            if (!empty($get['sign_out'])) {
                $where[] = ['a.sign_out', '=', $get['sign_out']];
            }
        }

        if (isset($get['like'])) {
            if (!empty($get['like'])) {
                $where[] = ['a.like', '=', $get['like']];
            }
        }


        $where[] = ['a.courses_id', '=', $school_id];

        $total = Db::table('o_qxt_user')
            ->alias('a')
            ->where($where)
            ->count();

        $rows = Db::table('o_qxt_user')
            ->alias('a')
            ->join('o_members b', 'b.id=a.uid')
            ->field('a.*, b.userid, b.name, b.department_name, b.division, b.mobile')
            ->where($where)
            ->page($get['page'], $get['limit'])
            ->select()->toArray();

        foreach ($rows as &$v) {
            $v['mobile'] = decrypts($v['mobile']);
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                } else {
                    $v['userid'] = $v['userid'];
                }
            } else {
                $v['userid'] = $v['userid'];
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function deleteMembers(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        $id = explode(',',trim($id,','));

        Db::startTrans();
        try {
            foreach ($id as $key => $value) {
                $qxt_user = Db::name('qxt_user')->where('id', '=', $value)->find();
                if (!$qxt_user) {
                    return $this->outputAjax('参数错误！');
                }
                if ($qxt_user['reg_type'] == 2) {
                    $user_name = Db::name('members')->where('id','=', $qxt_user['uid'])->column('name');
                    return $this->outputAjax(implode('、',$user_name).'为自主注册学员不可删除！');
                }
                if (!Db::name('qxt_user')->where('id', '=', $value)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[1]！');
                }
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    public function user(Request $request)
    {
        $school_id = $request->param('school_id');
        View::assign('school_id', $school_id);
        return View::fetch();
    }

    public function saveUser(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $school_id = $request->post('school_id');
        $uid = $request->post('id');

        if(!$school_id){
            return $this->outputAjax('缺少班级id！');
        }

        try {
            $uids = explode(',',$uid);
            if(!is_array($uids) || count($uids) <= 0){
                return $this->outputAjax('请选择学员！');
            }


            $t = [];
            $t['courses_id'] = $school_id;
            $t['reg_type'] = 1;
            $t['add_time'] = time();

            foreach ($uids as $key => $value) {
                $res = Db::name('qxt_user')
                    ->where('uid', '=', $value)
                    ->where('courses_id', '=', $school_id)
                    ->find();
                if($res){
                    continue;
                }
                $t['uid'] = $value;
                Db::name('qxt_user')->insert($t);
            }
            return $this->outputAjax('添加成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }



    //文件批量导入学员
    public function import(Request $request)
    {
        $school_id = $request->param('school_id');
        View::assign('school_id', $school_id);
        return View::fetch();
    }


    public function executeImport(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');

        $school_id = $request->param('school_id');

        if(empty($school_id)) {
            return $this->outputAjax('参数缺失', 2);
        }

        try {

            // 获取excel表格数据
            $result = get_excel_info($filename);
            if ($result['code'] == 1) {
                return $this->outputAjax($result['msg'], 2);
            }

            $i = 0;
            foreach ($result['data'] as $key => $value) {
                $userid = $value[0];

                $user = Db::name('members')
                    ->where('userid', '=', $userid)
                    ->field('id, userid')
                    ->find();
                if (!$user) {
                    continue;
                }

                $res = Db::name('qxt_user')
                    ->where('uid', '=', $user['id'])
                    ->where('courses_id', '=', $school_id)
                    ->find();
                if($res) {
                    continue;
                }

                $newValue = [
                    'courses_id' => $school_id,
                    'reg_type' => 0,
                    'add_time' => time(),
                    'uid' => $user['id'],
                ];
                $f = Db::name('qxt_user')->insert($newValue);
                if ($f) {
                    $i++;
                }
            }
            return $this->outputAjax('导入成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage(), 2);
        }
    }
}